﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBService;
using DBService.ViewDatas;
using System.Windows.Forms;



public partial class Site : System.Web.UI.MasterPage
{
    public string Root = String.Empty;

    public string FacebookLoginLink { get; set; }

    protected void Page_Init(object sender, EventArgs e)
    {
        Root = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/" + Request.ApplicationPath;
        Root += Root.EndsWith("/") ? "" : "/";
        string extended = ",publish_stream";
        #region fb login
        string url = "http://revio.ge/fblogin.aspx";
        string login = "https://www.facebook.com/dialog/oauth?client_id=296010147167377" +
                       "&redirect_uri=" + url + "&state=" + Guid.NewGuid().ToString().Replace("-", "") + "&scope=user_birthday,email" + extended;
        FacebookLoginLink = RegButtonLink.HRef = fbLogin.HRef = login;
        #endregion

        User usr = GetAuthedUserObject();
        if (usr == null)
        {
            AuthorizedPlace.Visible = false;
            SignInPlace.Visible = true;
            RegButton.Visible = true;
        }
        else
        {
            RegButton.Visible = false;
            AuthorizedPlace.Visible = true;
            SignInPlace.Visible = false;
            AuthUserFullName.InnerText = usr.FirstName;// +" " + usr.LastName;
            UserAvatar.Src =
            usr.FaceID.HasValue ? String.Format("http://graph.facebook.com/{0}/picture?width=50&height=50", usr.FaceID.ToString()) : usr.Avatar;
            fbLogin.Visible = false;
        }
    }

    protected void btnSmallSearch_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtSmallSearch.Value))
        {
            Session["keyword"] = txtSmallSearch.Value;
            Response.Redirect("SearchResult.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
    }

    protected void btnProfile_Click(object sender, EventArgs e)
    {
        Response.Redirect("userprofile.aspx?id=" + Session["UserID"]);
    }

    protected void SignMeIn_Click(object s, EventArgs e)
    {
        var ma = new ModelAdapter();
        User usr;
        if (ma.AuthenticateUser(MailSign.Value, PasswordSign.Value, out usr))
        {
            AuthorizedPlace.Visible = true;
            SignInPlace.Visible = false;
            AuthUserFullName.InnerText = usr.FirstName;// +" " + usr.LastName;

            if (String.IsNullOrEmpty(usr.Avatar))
            {
                UserAvatar.Src = "images/no-avatar.jpeg";
                Session["Avatar"] = "images/no-avatar.jpeg";
            }
            else
            {
                UserAvatar.Src = "upload/" + usr.Avatar;
                Session["Avatar"] = "upload/" + usr.Avatar;
            }
            Session["UserID"] = usr.UserID;
            Session["UserType"] = usr.UserType;
            Session["Email"] = usr.Email;
            Session["FirstName"] = usr.FirstName;
            Session["LastName"] = usr.LastName;
            Session["Gender"] = usr.Gender;
            Session["Likes"] = usr.Likes;
            Session["Dislikes"] = usr.Dislikes;
            Session["DateOfBirth"] = usr.DateOfBirth;
            Session["FaceID"] = usr.FaceID;
            Response.Redirect(Request.Url.OriginalString);
        }
        else
        {
            Script.Text = "<script>alert('თქვენ ვერ გაიარეთ ავტორიზაცია!');</script>";
        }
    }

    public User GetAuthedUserObject()
    {
        ModelAdapter service = new ModelAdapter();

        if (Session["UserID"] == null && Request.Cookies["UserInfo"] == null)
        {
            return null;
        }
        User usr = new User();
        if (Session["UserID"] != null)
        {
           // return null;
            usr.UserID = (int)Session["UserID"];
            usr.UserType = (short)Session["UserType"];
            usr.Avatar = Session["Avatar"].ToString();
            usr.Email = Session["Email"].ToString();
            usr.FirstName = Session["FirstName"].ToString();
            usr.LastName = Session["FirstName"].ToString();
            usr.Gender = (bool?)Session["Gender"];
            usr.Likes = (int?)Session["Likes"];
            usr.Dislikes = (int?)Session["Dislikes"];
            usr.DateOfBirth = (DateTime?)Session["DateOfBirth"];
            usr.FaceID = (long?)Session["FaceID"];
        }
        else if (Request.Cookies["UserInfo"] != null)
        {
            HttpCookie cookies = Request.Cookies["UserInfo"];
            usr.UserID = int.Parse(cookies["UserID"]/*Request.Cookies["UserID"].Value*/);
            usr.UserType = short.Parse(cookies["UserType"]);
            usr.Avatar = cookies["Avatar"].ToString();
            usr.Email = cookies["Email"].ToString();
            usr.FirstName = cookies["FirstName"].ToString();
            usr.LastName = cookies["FirstName"].ToString();
            usr.Likes = int.Parse(cookies["Likes"].ToString());
            usr.Dislikes = int.Parse(cookies["Dislikes"]);

            if (cookies["FaceID"] == "")
                usr.FaceID = null;
            else
                usr.FaceID = long.Parse(cookies["FaceID"]);
            if (cookies["DateOfBirth"] == "")
                usr.DateOfBirth = null;
            else
                usr.DateOfBirth = DateTime.Parse(cookies["DateOfBirth"]);
            if (cookies["Gender"] == "")
                usr.Gender = null;
            else
                usr.Gender = bool.Parse(cookies["Gender"]);
            LoginUser(usr);
        }
        return usr;
    }

    protected void LoginUser(User usr)
    {
        Session["Avatar"] =
            usr.FaceID.HasValue ? String.Format("http://graph.facebook.com/{0}/picture?width=50&height=50", usr.FaceID.ToString()) : "upload/" + usr.Avatar;
        Session["FaceID"] = usr.FaceID;
        Session["UserID"] = usr.UserID;
        Session["UserType"] = usr.UserType;
        Session["Email"] = usr.Email;
        Session["FirstName"] = usr.FirstName;
        Session["LastName"] = usr.LastName;
        Session["Gender"] = usr.Gender;
        Session["Likes"] = usr.Likes;
        Session["Dislikes"] = usr.Dislikes;
        Session["DateOfBirth"] = usr.DateOfBirth;
    }

    protected void LogOut_Click(object sender, EventArgs e)
    {
        Session.Clear();
        Session.Abandon();

        var cookis = Request.Cookies["UserInfo"];
        if (cookis != null)
        {
            cookis.Expires = DateTime.Now.AddDays(-1d);
            Response.Cookies.Add(cookis);
        }
        Response.Redirect("default.aspx");
    }
}
